package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.IDStarAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j // log日志对象
@Service // 交给IOC容器管理
public class DishServiceImpl implements DishService {

    //注入dishMapper对象
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional //0.开启事务 (涉及到多张表的增删改查操作需要开事务)  一行移动位置快捷键
    public void addDish(DishDTO dto) {
        //1.构造菜品基本信息数据, 将器存入dish表中
        //1.1构造对象
        Dish dish = new Dish();
        //1.2属性拷贝 -- 并补齐缺失属性
        BeanUtils.copyProperties(dto, dish);
        //1.3调用Mapper层, 将数据存入到dish表中
        dishMapper.insert(dish);
        //2.构造菜品口味列表数据, 将其存入dish_flavor表中
        //2.1获取口味数据
        List<DishFlavor> dishFlavorList = dto.getFlavors();
        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            //2.2关联菜品id
            dishFlavorList.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
        }

        //2.3将口味表数据,存储dish_flavors表中
        dishFlavorMapper.insertBatch(dishFlavorList);
    }

    /**
     * 菜品分页查询
     *
     * @param dto
     * @return
     */

    @Override
    public PageResult pageQuery(DishPageQueryDTO dto) {
        //1.设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //2.调用Mapper的列表查询方法, 强转成Page
        Page<DishVO> page = dishMapper.list(dto);
        //3.封装成PageResult对象并返回
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Transactional // 0.开启事务
    @Override
    public void delete(List<Long> ids) {
        //1.删除菜品之前, 需要判断菜品是否起售, 起售中不允许删除
        //1.1一条一条查询
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            //1.2判断是否是起售状态
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });
        //2.需要判断菜品是否被套餐关联, 关联了也不允许删除
        Integer count = setmealDishMapper.selectById(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.调用Mapper方法,删除菜品基本信息, dish表
        dishMapper.deleteBatch(ids);
        //4.调用Mapper方法,删除口味列表信息, dish_flavor表
        dishFlavorMapper.deleteBatch(ids);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getDishById(Long id) {
        //1.根据菜品id查询菜品基本信息
        Dish dish = dishMapper.selectById(id);
        //2.根据菜品id查询口味列表数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectByid(id);
        //3.构造DishVO对象并返回
        //3.1创建DishVO对象, 并拷贝属性
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        //3.2补齐口味属性
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dto
     */
    @Override
    @Transactional //0.开启事务
    public void updateDish(DishDTO dto) {
        //1.修改菜品的基本信息, dish表
        //1.1构造dish对象 --> 不可以缺失时间等字段, 并进行属性拷贝
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.update(dish);
        //2.修改口味列表信息, dish_flavor表
        //由于口味数据可能增加、可能删除、还可能修改口味的值, 涉及到增删改查, 所以先全部删除,再添加数据
        dishFlavorMapper.deleteByDishId(dto.getId());
        //2.2获取口味列表数据
        List<DishFlavor> flavors = dto.getFlavors();
        //2.3非空判断, 补充dish_id字段
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 菜品起售与停售
     *
     * @param status
     * @param id
     */
    @Override
    @Transactional //0.涉及到dish、setmale、setmeal_dish表, 开启事务
    public void enableOrDisable(Integer status, Long id) {
        //1.调用Mapper获取与当前菜品关联的套餐, 并获取关联对象
        List<SetmealDish> setmealDishList = setmealDishMapper.select(id);
        //2.判断是否有套餐关联, 有就修改套餐表的status
        if (setmealDishList != null && !setmealDishList.isEmpty()) {
            setmealDishList.forEach(setmealDish -> {
                //2.1构建对象, 并于后面复用
                Setmeal setmeal = Setmeal
                        .builder()
                        .status(status)
                        .id(setmealDish.getId())
                        .build();
                setmealMapper.update(setmeal);
            });
        }
        //3.修改dish表的status
        //3.1构造dish对象
        Dish dish = Dish
                .builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
    }


    /**
     *
     * 根据菜品id查询菜品列表
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getById(Long categoryId) {
        //构造对象
        Dish dish = Dish.builder()
                .status(StatusConstant.ENABLE) // 不起售的不允许加到套餐里面
                .categoryId(categoryId) // 是类型id
                .build();
        //1.直接调用mapper层,进行获取数据
        List<Dish> dishList = dishMapper.select(dish);
        //2.响应结果
        return dishList;
    }



    /**
     * 条件查询菜品和口味 --- 直接导入的
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByid(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
